const { exec, escape } = require("../db/mysql");
const xss = require("xss");

//获取博客列表
const getList = (author, keyword) => {
    let sql = `select * from blog where 1=1 `;
    if (author) {
        sql += `and author="${author}" `;
    }
    if (keyword) {
        sql += `and content like "%${keyword}%" `
    }
    sql += "order by createTime desc";

    return exec(sql);
}
//获取博客文章
const getDetail = (id) => {
    let sql = `select * from blog where id=${id}`;
    return exec(sql);
}
//新建博客
const newBlog = (postData) => {
    let { title, author, content, createTime } = postData;
    title = xss(escape(title));
    author = xss(escape(author));
    content = xss(escape(content));

    let sql = `insert into blog (title, author, content, createTime) value ("${title}", "${author}", "${content}", ${createTime})`;
    return exec(sql);
}
//更新博客
const updateBlog = (postData) => {
    let { id, title, content } = postData;
    title = xss(escape(title));
    author = xss(escape(author));
    content = xss(escape(content));

    let sql = `update blog set title="${title}",content="${content}" where id=${id}`;

    return exec(sql);
}
//删除博客
const deleteBlog = (postData) => {
    const { id } = postData;
    let sql = `delete from blog where id=${id}`;
    return exec(sql);
}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    deleteBlog
}